#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# -= project0/.py coding by Scott in 2019-06-05 16:01 with IDE:PyCharm =-
import hashlib
import json

import requests

from config.constants import get_user_info_url
from utils.at_ccs import get_access_token


def verify(request_args):
    if len(request_args) == 4:
        try:
            signature = request_args.get('signature')
            timestamp = request_args.get('timestamp')
            nonce = request_args.get('nonce')
            token = 'qwer1234'  # Todo 设置成变量
            temp_list = [token, timestamp, nonce]
            temp_list.sort()
            temp = ''.join(temp_list)
            sha1 = hashlib.sha1(temp.encode('utf-8'))
            hashcode = sha1.hexdigest()  # 以微信规则进行加密运算

            # 将加密后的字符串和signatrue对比，如果相同返回echostr,表示验证成功
            if hashcode == signature:
                return True
            else:
                print('校验错误')
                return False

        except Exception as e:
            print(e)
            return False
    else:
        return False


def get_user_info(appid, open_id):
    access_token = get_access_token(appid)
    rp = requests.get(get_user_info_url.format(access_token, open_id))
    rp_data = json.loads(rp.text)
    if rp_data.get('errcode') or not access_token:
        return {'nickname': '用户'}
    return rp_data
